import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;

public class DataFileStorer implements Runnable{
	
	private HashMap<Integer, Integer> stations;
	private RandomAccessFile file;
	
	private String currentDate;
	private String currentHour;
	
	private Queue<Data> buffer;
	
	private static int DATA_LENGTH = 83;
	private int counter = 0;
	private int measurementAmount = 0;
	
	public DataFileStorer(HashMap<Integer, Integer> stations){
		this.stations = stations;			
		this.buffer = new LinkedList<Data>();
		currentDate = getCurrentDate();
		currentHour = getCurrentHour();
		createFile();
	}
	
	//Create a file within a directory called "MONTH" with the name "HOUR"
	public void createFile(){
		try {
			file = new RandomAccessFile(new File("Measurements\\" + currentDate + "\\" + currentHour + ".txt"), "rw");
			System.out.println("File "+currentHour+" is aangemaakt");
		} catch (FileNotFoundException e) {
			if(!new File("Measurements").exists()){
				new File("Measurements").mkdir();
				System.out.println("Map measurements is aangemaakt");
			} else{
				new File("Measurements\\" + currentDate).mkdir();
				System.out.println("Map "+currentDate+" is aangemaakt");
			}			
			createFile();
		}		
	}
	
	public String getCurrentDate(){
		SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyyy");
		return dateFormat.format(new Date(System.currentTimeMillis()));		
	}
	
	public String getCurrentHour(){
		SimpleDateFormat hourFormat = new SimpleDateFormat("k");
		return hourFormat.format(new Date(System.currentTimeMillis()));
	}
	
	//Add to buffer
	public synchronized void addToBuffer(Data data){		
		buffer.add(data);		
	}
	
	//Get from buffer
	public synchronized Data removeFromBuffer(){
		return buffer.poll();
	}
	


	@Override
	public void run() {	

		Boolean empty = null;
		System.out.println("FileStorer started");
		System.out.println("Waiting for full buffer");	
		System.out.println("Er zijn genoeg objecten");

		while(true){				
			try {				
				empty = buffer.isEmpty();				
				if(!empty){	
					synchronized(this){
						Data data = removeFromBuffer();
						int index = stations.get(data.getStn());					
						if(counter == 8000){
							counter = 0;
							measurementAmount++;							
						}						
						file.seek((measurementAmount*(DATA_LENGTH*8000))+(DATA_LENGTH*index));
						String datas = data.getAllData();

						file.writeBytes(datas);		
						
						counter++;
					}											
				}				
				
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			empty = null;
		}
	}
}